<?php
defined('BASEPATH') OR exit('No direct script access allowed');

define('BALANCE_TYPE', 1); //余额支付类型
define('WECHAT_TYPE', 2);  //微信支付类型
define('ALIPAY_TYPE', 3);  //支付宝支付类型

/**
 * 产品
 * @author www.dingwei.cn
 */
class Pay extends MY_Controller {
	
	/**
	 * 支付模型
	 * @var MerchantPayModel
	 */
	public $mPay;

	/**
	 * 订单模型
	 * @var MerchantPromotionModel
	 */
	public $mPro;
	
	public function __construct(){
		parent::__construct();
		$this->loadModel('MerchantPayModel', 'mPay', 'merchant');
		$this->loadModel('MerchantPromotionModel', 'mPro', 'merchant');

	}



	////////////////////////////////////////////////////
	//+-----------------------------------------------
	//|	回调
	//+----------------------------------------------
	/**
	 * 支付宝回调
	 */
	public function zfbCallback(){
        //保存预下单参数
        if(!($this->mPay->savePayOrder(array('callback'=>json_encode($_POST)), post('out_trade_no')))){
            echo "fail" ; exit;
        }

        include APPPATH.'libraries/AliPay/AopSdk.php';
        $aop = new \AopClient;

        $config = getCustomConfig('alipay',get_instance()->port);
        $aop->alipayrsaPublicKey = $config['alipayrsaPublicKey'] ;
        //验证签名
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");

        if(!$flag){
            echo "fail" ; exit;
        }

        $status = post('trade_status');
        $code = post('out_trade_no');
        $total_fee = post('total_amount');//总金额

        if($status == 'TRADE_FINISHED' || $status == 'TRADE_SUCCESS') {

            //验证预支付订单是否存在
            $payInfo = $this->mPay->getInfo(0, $code);
            if(!$payInfo){
                echo "fail" ; exit;
            }

            //验证红包是否存在
            $bonusInfo = $this->mPro->getBonusInfo(0, $payInfo['merchant_id'], $code);
            if(!$bonusInfo){
                echo "fail" ; exit;
            }

            //验证金额及状态
            if($bonusInfo['amount'] != $total_fee || $bonusInfo['pay_status'] != 1){
                echo "fail" ; exit;
            }

            $this->db->trans_begin();

            //保存预下单状态
            if(!($this->mPay->savePayOrder(array('status' => 2,'paytime' => time()), $code))){
                $this->db->trans_rollback();
                echo "fail" ; exit;
            }

            //修改红包支付状态
            if(!($this->mPro->save(array('pay_status' => 2), 0, $code))){
                $this->db->trans_rollback();
                echo "fail" ; exit;
            }

            $this->db->trans_commit();
            echo "success";exit;

        }else if ($status == 'WAIT_BUYER_PAY ') {
            echo "success";exit;
        }else {
            echo "fail";exit;
        }

	}
	
	/**
	 * 微信支付回调
	 */
	public function wxCallback(){
        $postStr = file_get_contents('php://input');
        $xmlObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        $str = (array)$xmlObj;//如果要数组 强制类型状态
        if(!($this->mPay->savePayOrder(array('callback'=>$postStr), $xmlObj->out_trade_no))){
            echo "fail" ; exit;
        }
        $notify = new PayNotifyCallBack();
        $notify->Handle(false);
	}

}

include APPPATH.'libraries/WxpayAPI2/lib/WxPay.Api.php';
include APPPATH.'libraries/WxpayAPI2/lib/WxPay.Notify.php';
class PayNotifyCallBack extends WxPayNotify {

    //查询订单
    public function Queryorder($transaction_id)
    {

        $input = new WxPayOrderQuery();
        $input->SetTransaction_id($transaction_id);
        $result = WxPayApi::orderQuery($input);

        if(array_key_exists("return_code", $result)
            && array_key_exists("result_code", $result)
            && $result["return_code"] == "SUCCESS"
            && $result["result_code"] == "SUCCESS")
        {
            $code = $result['out_trade_no'];
            $total_fee = $result['total_fee'];//支付金额
            $CI =& get_instance();

            //验证预支付订单是否存在
            $payInfo = $CI->mPay->getInfo(0, $code);
            if(!$payInfo){
                return false;
            }

            //验证红包是否存在
            $bonusInfo = $CI->mPro->getBonusInfo(0, $payInfo['merchant_id'], $code);
            if(!$bonusInfo){
                return false;
            }

            //验证金额及状态
            if($bonusInfo['amount'] != $total_fee/100 || $bonusInfo['pay_status'] != 1){
                return false;
            }

            $CI->db->trans_begin();

            //保存预下单状态
            if(!($CI->mPay->savePayOrder(array('status' => 2,'paytime' => time()), $code))){
                $CI->db->trans_rollback();
                return false;
            }

            //修改红包支付状态
            if(!($CI->mPro->save(array('pay_status' => 2), 0, $code))){
                $CI->db->trans_rollback();
                return false;
            }

            $CI->db->trans_commit();
            return true;
        }

        return false;
    }

    //重写回调处理函数
    public function NotifyProcess($data, &$msg)
    {

        $notfiyOutput = array();
        if(!array_key_exists("transaction_id", $data)){
            $msg = "输入参数不正确";

            return false;
        }

        //查询订单，判断订单真实性
        if(!$this->Queryorder($data["transaction_id"])){
            $msg = "订单查询失败";

            return false;
        }

        return true;
    }
}

